<template>
  <el-dialog
    :title="title === 'creatives' ? '素材库': title === 'originalCreatives'? '原始素材' :'被拒素材' "
    :visible.sync="dialogVisible"
    :append-to-body="true"
    :close-on-click-modal="false"
    width="80%"
    :before-close="handleClose">
    <!--  素材库、被拒素材、原始素材table  -->
    <basic-container>
      <avue-crud :option="option"
                 :table-loading="loading"
                 :data="data"
                 :page.sync="page"
                 :search.sync="search"
                 v-model="form"
                 ref="crud"
                 @search-change="searchChange"
                 @search-reset="searchReset"
                 @selection-change="selectionChange"
                 @current-change="currentChange"
                 @size-change="sizeChange"
                 @refresh-change="refreshChange"
                 @on-load="onLoad">

        <template slot-scope="{row}" slot="creativeUrl">
          <div class="cell">
            <span v-if="row.creativeUrl === '-2'">上传失败</span>
            <span v-if="row.creativeUrl === '-1'">上传中</span>
            <div>
              <img style="max-width: 100%;width: auto;max-height: 200px;height: auto"
                   :src="row.thumbnailUrl"
                   alt="">
            </div>
          </div>
        </template>
        <template slot-scope="{size}" slot="shortIdSearch">
          <el-form-item prop="shortId">
            <el-input id="id-offer-componets-creativerequestappend-shortId" placeholder="请输入短ID" :size="size"  v-model="search.stringShortId" clearable ></el-input>
          </el-form-item>
        </template>
        <template slot-scope="{row}" slot="designer">
          {{ designerShow(row.designer) }}
        </template>
        <template slot-scope="{row}" slot="link">
          <div class="cell">
            <span v-if="row.link === '-2'">上传失败</span>
            <span v-if="row.link === '-1'">上传中</span>
            <div v-if="row.link !== '-2' && row.link !== '-1'">
              <img style="max-width: 100%;width: auto;max-height: 200px;height: auto"
                   :src="row.thumbnailUrl"
                   alt="">
            </div>
          </div>
        </template>
      </avue-crud>
    </basic-container>

    <span slot="footer" class="dialog-footer">
      <el-button id="id-offer-componets-creativerequestappend-handleClose" @click="handleClose">取 消</el-button>
      <el-button id="id-offer-componets-creativerequestappend-handleSubmit" type="primary"
                 @click="handleSubmit">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>

import {mapGetters} from "vuex";
import {getList as getCreativeList, getDesigner} from "@/api/offer/creative";
import {getRejectedCreativeList} from "@/api/offer/creativerequest";
import {getList as getOrigincreativeList, getTagList} from "@/api/offer/origincreative";
import {getSysDictList} from "@/api/system/dict";
import {findObject} from "@/util/util";

const tagsSearchList = []
export default {
  name: "creativeRequestAppend",
  data() {
    return {
      loading: true,
      data: [],
      selectionList: [],
      search: {},
      form: {
        type: 0,
      },
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
        offerId: null,
      },
      designerList: [],
      option: {
        searchLabelWidth:150,
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        selection: true,
        addBtn: false,
        editBtn: false,
        viewBtn: false,
        delBtn: false,
        columnBtn: false,
        menu: false,
        menuWidth: 180,
        dialogClickModal: false,
        column: []
      },
      originCreativeAddDialogVisible: false,
    };
  },
  computed: {
    ...mapGetters(["permission"]),
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    }
  },
  props: {
    dialogVisible: {
      type: Boolean
    },
    title: {
      type: String,
    },
    index: {
      type: String,
    },
    existedCreativeIds: {
      type: String,
    },
    creativeRequestId: {
      type: String,
    },
    offerId: {
      type: String,
    },
  },
  watch: {
    dialogVisible: {
      deep: true,
      handler(value) {
        if (!value) {
          // 取消弹窗时不调用
          return;
        }
        this.page.offerId = this.offerId
        let title = this.title;
        const creativesColumn = [
          // {
          //   labelWidth: 200
          // },
          {
            label: "短ID",
            prop: "shortId",
            addDisplay: false,
            slot: true,
            search: true,
            searchslot: true,
          },
          {
            label: "素材名称",
            prop: "name",
            addDisplay: false,
            slot: true,
            search: true
          },
          {
            label: "本地文件名",
            prop: "localFilename",
            addDisplay: false,
            slot: true,
            search: true,
          },
          {
            label: "媒体",
            prop: "platform",
            type: 'select',
            multiple: true,
            dataType: 'string',
            dicData: [],
            props: {
              label: "dictValue",
              value: "dictKey"
            },
            search: true,
            searchMultiple: true,
            rules: [{
              required: true,
              message: "请输入名称",
              trigger: "blur"
            }]
          },
          {
            label: "类型",
            prop: "type",
            addDisplay: false,
            editDisplay: false,
            type: 'select',
            dicData: [
              {label: '图片', value: 0},
              {label: '视频', value: 1},
            ],
          },
          {
            label: "版本号",
            prop: "version",
            addDisplay: false,
            editDisplay: false
          },
          {
            label: "审批状态",
            prop: "status",
            type: 'select',
            addDisplay: false,
            editDisplay: false,
            dicData: [
              {label: '等待提交', value: 0},
              {label: '等待审核', value: 1},
              {label: '审核通过', value: 2},
              {label: '审核拒绝', value: 3},
              {label: '禁用', value: 4}
            ],
            rules: [{
              required: true,
              message: "请输入标签",
              trigger: "blur"
            }]
          },
          {
            label: "素材",
            prop: "creativeUrl",
            slot: true,
            rules: [{
              required: true,
              message: "请输入素材",
              trigger: "blur"
            }],
          },
          {
            label: "标签",
            prop: "tags",
            rules: [{
              required: true,
              message: "请输入标签",
              trigger: "blur"
            }],
          },
          {
            label: "设计者",
            prop: "designer",
            rules: [{
              required: true,
              message: "请输入设计者",
              trigger: "blur"
            }],
            type: 'select',
            dicUrl: '/api/blade-user/select/user?statusList=0,1,2&isAll=true',
            props: {
              label: "realName",
              value: "id"
            },
            multiple: true,
            search: true,
          },
          {
            label: "创建时间",
            prop: "createTime",
          },
          {
            label: "素材尺寸",
            prop: "sizeType",
            hide: true,
            addDisplay: false,
            editDisplay: false,
            search: true,
            type: 'select',
            dicData: [
              {label: "横幅", value: 'H'},
              {label: "竖幅", value: 'V'},
              {label: "方幅", value: 'S'},
            ],
          },
        ]
        const originalCreativeColumn = [
          {
            label: "名称",
            prop: "name",
            search: true,
            rules: [{
              required: true,
              message: "请输入名称",
              trigger: "blur",
              search: true
            }]
          },
          {
            label: "类型",
            prop: "type",
            dicData: [
              {label: '图片', value: 0},
              {label: '视频', value: 1},
            ],
            addDisplay: false,
            type: 'select',
          },
          {
            label: "素材",
            prop: "link",
            rules: [{
              required: true,
              message: "请输入素材链接",
              trigger: "blur"
            }],
          },
          {
            label: "标签",
            prop: "tag",
            dicData: tagsSearchList,
            search: true,
            type: 'select',
            searchFilterable: true,
          },
          {
            label: '创建人',
            prop: 'username',
            search: true,
            rules: [{
              required: false,
              message: "请输入创建人",
              trigger: "blur",
              search: true
            }],
          },
          {
            label: '创建时间',
            prop: 'createTime',
          }
        ]
        if (title === 'creatives') {
          //素材库
          this.option.column = creativesColumn
          this.initColumns();
          this.refreshChange();
        } else if (title === 'originalCreatives') {
          //原始素材
          this.option.column = originalCreativeColumn
          this.initColumns();
          this.refreshChange();
        } else if (title === 'rejectedCreatives') {
          //被拒素材
          this.option.column = creativesColumn
          this.initColumns();
          this.refreshChange();
        }
      }
    }
  },
  created() {
    getSysDictList('platforms').then(map => {
      this.platformList = map['platforms'];
      this.initColumns();
    });
  },
  mounted() {
    this.page.offerId = this.offerId;
    getTagList().then(res => {
      this.tagsList = res.data.data
      this.tagsList.map(item => {
        tagsSearchList.push({label: item, value: item})
      })
    })
    getDesigner(this.offerId).then(res => {
      this.designerList = res.data.data;
    });
  },
  methods: {
    initColumns() {
      let column = findObject(this.option.column, 'platform', 'prop')
      if (column != null) {
        column.dicData = this.platformList;
      }
    },
    checkShortId(rule, value, callback) {
      const shortReg = /^\d{3,6}$/;
      if (value !== '' && !shortReg.test(value)) {
        callback(new Error('请输入3-6位数字!'))
      } else {
        callback()
      }
    },
    designerShow(val) {
      let list = []
      if (val.length > 0) {
        val = val.split(',')
        this.designerList.map(item => {
          val.map(i => {
            if (item.id === i) {
              list.push(item.realName)
            }
          })
        })
      }
      return list.join(',')
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    selectionClear() {
      this.selectionList = [];
    },
    onLoad(page, params = {}) {

      this.loading = true;
      // 获取已存在中的素材ID
      params.excludedIds = this.existedCreativeIds;
      if (this.title === 'creatives') {
        //素材库
        getCreativeList(page.currentPage, page.pageSize, page.offerId, Object.assign(params, this.query)).then(res => {
          let data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
        });
      } else if (this.title === 'originalCreatives') {
        //原始素材
        getOrigincreativeList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          let data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
        });
      } else if (this.title === 'rejectedCreatives') {
        //审核拒绝
        params.status = 3
        getRejectedCreativeList(page.currentPage, page.pageSize, page.offerId, Object.assign(params, this.query), this.creativeRequestId).then(res => {
          let data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
        });
      }
      this.loading = false;
      this.selectionClear();
    },
    handleClose() {
      this.list = [{}]
      this.$emit('close-dialog')
      this.$refs.crud.searchReset()
    },
    handleSubmit() {
      const selectionList = this.selectionList;
      if (selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$emit('append-creatives', selectionList, this.title, this.index)
      this.handleClose()
      this.$emit('close-dialog')
    },
  }
}
</script>

<style lang="scss" scoped>
.text {
  width: 45px;
  height: 30px;
  float: left;
  font-size: 13px;
  margin-top: 3px;
  color: #72767b
}

.search-circle {
  border-radius: 50%;
  border: 1px solid #dcdfe6;
  width: 30px;
  height: 30px;
  padding: 0;
  margin-right: 0;
}
</style>
